<template>
  <div>选择课题：</div>
  <div class="table-box">
    <vxe-table :data="selectTable">
      <vxe-column field="id" title="课题编号" />
      <vxe-column field="name" title="课题名称" />
      <vxe-column field="leader" title="课题负责人" />
      <vxe-column field="type" title="课题类型">
        <template #default="{ row }">
          <span>
            {{ dictStore.getDictLabelForValue('topic_type', row.type) }}
          </span>
        </template>
      </vxe-column>
      <vxe-column field="subjectAreaText" title="专业领域" />
      <vxe-column
        field="researchStartDate"
        title="研究开始时间"
        :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
      />
      <vxe-column
        field="researchEndDate"
        title="研究结束时间"
        :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
      />
      <vxe-column field="estimatedBudget" title="预计投入经费(万元)" />
      <vxe-column field="externalCooperationRequired" title="是否需要外协">
        <template #default="{ row }">
          <span>
            {{
              dictStore.getDictLabelForValue(
                'yes_no',
                row.externalCooperationRequired
              )
            }}
          </span>
        </template>
      </vxe-column>
      <vxe-column field="leadingUnitName" title="承担单位" />
      <vxe-column field="collaboratingUnitNames" title="协作单位" />
    </vxe-table>
  </div>
  <el-button
    style="margin-top: 20px"
    type="primary"
    :icon="Plus"
    @click="visible = true"
  >
    增加课题
  </el-button>

  <vxe-modal
    v-model="visible"
    title="搜索课题"
    show-footer
    transfer
    fullscreen
    destroy-on-close
  >
    <template #default>
      <vxe-form ref="queryform" :data="queryForm" title-align="right">
        <vxe-form-item title="课题类型" field="type" :item-render="{}">
          <template #default="{ data }">
            <el-select
              v-model="data.type"
              placeholder="请选择"
              style="width: 210px"
            >
              <el-option
                v-for="item in dictStore.getDictType('topic_type')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="专业领域" field="subjectArea" :item-render="{}">
          <template #default="{ data }">
            <el-cascader
              v-model="data.subjectArea"
              :options="majorsTrees"
              :props="optionProps"
              placeholder="请选择"
              style="width: 300px"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item title="承担单位" field="leadingUnitId" :item-render="{}">
          <template #default="{ data }">
            <el-select
              v-model="data.leadingUnitId"
              placeholder="请选择"
              style="width: 210px"
            >
              <el-option
                v-for="item in depts"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="项目级别" field="projectLevel" :item-render="{}">
          <template #default="{ data }">
            <el-select
              v-model="data.projectLevel"
              placeholder="请选择"
              style="width: 210px"
            >
              <el-option
                v-for="item in dictStore.getDictType('project_level')"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="项目类型" field="projectType" :item-render="{}">
          <template #default="{ data }">
            <el-cascader
              v-model="data.projectType"
              :options="projectTypes"
              :props="optionProps"
              placeholder="请选择"
              style="width: 300px"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="是否重点项目"
          field="keyProject"
          :item-render="{}"
        >
          <template #default="{ data }">
            <el-select
              v-model="data.keyProject"
              placeholder="请选择"
              style="width: 210px"
            >
              <el-option
                v-for="item in dictStore.getDictType('yes_no')"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="关键字" field="keywords" :item-render="{}">
          <template #default="{ data }">
            <el-select v-model="data.keywords" placeholder="请选择">
              <el-option label="课题名称" value="topicName" />
              <el-option label="课题编号" value="topicCode" />
              <el-option label="课题负责人" value="topicLeader" />
              <el-option label="项目名称" value="projectName" />
              <el-option label="项目编号" value="topicCode" />
              <el-option label="项目负责人" value="projectLeaderName" />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item>
          <vxe-button status="primary" content="搜索" @click="queryData" />
          <vxe-button type="reset" content="重置" />
        </vxe-form-item>
      </vxe-form>
      <vxe-table
        ref="tableRef"
        :data="tableData"
        @checkbox-all="selectAllChangeEvent"
        @checkbox-change="selectChangeEvent"
      >
        <vxe-column type="checkbox" width="60" />
        <vxe-column field="id" title="课题编号" />
        <vxe-column field="name" title="课题名称" />
        <vxe-column field="leader" title="课题负责人" />
        <vxe-column field="type" title="课题类型">
          <template #default="{ row }">
            <span>
              {{ dictStore.getDictLabelForValue('topic_type', row.type) }}
            </span>
          </template>
        </vxe-column>
        <vxe-column field="subjectAreaText" title="专业领域" />
        <vxe-column
          field="researchStartDate"
          title="研究开始时间"
          :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
        />
        <vxe-column
          field="researchEndDate"
          title="研究结束时间"
          :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
        />
        <vxe-column field="estimatedBudget" title="预计投入经费(万元)" />
        <vxe-column field="externalCooperationRequired" title="是否需要外协">
          <template #default="{ row }">
            <span>
              {{
                dictStore.getDictLabelForValue(
                  'yes_no',
                  row.externalCooperationRequired
                )
              }}
            </span>
          </template>
        </vxe-column>
        <vxe-column field="leadingUnitName" title="承担单位" />
        <vxe-column field="collaboratingUnitNames" title="协作单位" />
      </vxe-table>
      <el-pagination
        background
        :current-page="queryForm.pageNo"
        :layout="layout"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script setup>
  import { Plus } from '@element-plus/icons-vue'
  import { useDictStore } from '@/store/modules/dict'
  import { selectTopicPage } from '@/api/project/index'
  import { getDictTypeTree } from '@/api/system/dict/dict.data'
  import { getDeptPage } from '@/api/system/dept/index'

  const dictStore = useDictStore()
  const $baseMessage = inject('$baseMessage')

  const tableRef = ref()
  const visible = ref(false)
  const depts = ref([])
  const majorsTrees = ref([])
  const projectTypes = ref([])
  const optionProps = ref({
    value: 'value',
    label: 'label',
    emitPath: false, //只传最后一级id
  })

  const queryForm = reactive({
    pageNo: 1,
    pageSize: 10,
  })

  const selectData = ref([])
  const tableData = ref([])
  const selectTable = ref([])
  const total = ref(0)
  const listLoading = ref(false)
  const layout = 'total, sizes, prev, pager, next, jumper'

  watch(visible, (value) => {
    if (value) {
      queryData()
    }
  })

  const selectAllChangeEvent = () => {
    const $table = tableRef.value
    if ($table) {
      const records = $table.getCheckboxRecords()
      if (records.length > 0) {
        const set = new Set([...selectData.value, ...records])
        selectData.value = Array.from(set)
      } else {
        selectData.value = selectData.value.filter(
          (itm) => !records.some((x) => x.id === itm.id)
        )
      }
    }
  }
  const selectChangeEvent = ({ row }) => {
    const $table = tableRef.value
    if ($table) {
      const index = selectData.value.findIndex((itm) => itm.id === row.id)
      if (index >= 0) {
        selectData.value.splice(index, 1)
      } else {
        selectData.value.push(row)
      }
    }
  }

  const fetchData = async () => {
    listLoading.value = true
    const params = { ...queryForm, queryType: 3 }
    if (params.keywords) {
      params[params.keywords] = params.keywordscontent
    }
    delete params.keywords
    delete params.keywordscontent
    selectTopicPage(params)
      .then((res) => {
        if (res.code == 0 || res.code == 200) {
          tableData.value = res.data.list || []
          total.value = res.data.total
          listLoading.value = false
          console.log(selectData.value)
          if (selectData.value.length > 0) {
            const arr = []
            tableData.value.forEach((item) => {
              if (selectData.value.findIndex((x) => x.id === item.id) >= 0) {
                arr.push(item)
              }
            })
            nextTick(() => {
              arr.forEach((item) => {
                tableRef.value.toggleCheckboxRow(item)
              })
            })
          }
        } else {
          listLoading.value = false
        }
      })
      .catch((err) => {
        listLoading.value = false
      })
  }

  const handleSizeChange = (val) => {
    queryForm.pageSize = val
    fetchData()
  }

  const handleCurrentChange = (val) => {
    queryForm.pageNo = val
    fetchData()
  }

  const queryData = () => {
    queryForm.pageNo = 1
    fetchData()
  }

  //获取专业领域数据
  const getMajorsTree = () => {
    getDictTypeTree({ parentId: 149 }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        majorsTrees.value = res.data.children || []
      }
    })
  }

  //获取项目类型
  const getProjectTypes = () => {
    getDictTypeTree({ parentId: 158 }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        projectTypes.value = res.data.children || []
      }
    })
  }

  const getDepts = () => {
    getDeptPage().then((res) => {
      if (res.code == 0 || res.code == 200) {
        depts.value = res.data || []
      }
    })
  }

  const handleConfirm = () => {
    if (!selectData.value.length) {
      return $baseMessage('请选择课题', 'error')
    }
    selectTable.value = [...selectData.value]
    visible.value = false
  }

  const handleCancel = () => {
    selectData.value = [...selectTable.value]
    visible.value = false
  }

  getMajorsTree()
  getProjectTypes()
  getDepts()

  defineExpose({ selectTable: selectTable })
</script>

<style lang="scss" scoped>
  .table-box {
    margin-top: 20px;
  }
</style>
